<template>
  <view class="page-container">
    <!-- 固定头部区域 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="title">发现</view>
      </view>

      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input-box">
          <text class="icon-search">🔍</text>
          <input type="text" class="search-input" placeholder="搜索智能体" placeholder-class="search-placeholder"
            v-model="searchKey" @confirm="handleSearch" />
        </view>
      </view>

      <!-- 标签栏 -->
      <scroll-view scroll-x class="tag-scroll" :show-scrollbar="false">
        <view v-for="(tag, index) in tags" :key="index" :class="['tag-item', currentTag === index ? 'active' : '']"
          @tap="switchTag(index)">
          {{ tag }}
        </view>
      </scroll-view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view 
      class="scrollable-content"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx + 88rpx + 88rpx)` }"
      scroll-y 
      @scrolltolower="loadMore" 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refresh"
    >
      <!-- banner区域 -->
      <view class="banner-box" @tap="handleBannerTap">
        <image src="" mode="aspectFill" class="banner-img" />
        <view class="banner-text">智能锁AI客服</view>
        <view class="banner-btn">快来试试吧</view>
      </view>

      <!-- AI列表 -->
      <view class="device-list">
        <view class="device-item" v-for="item in deviceList" :key="item.id">
          <image class="avatar" :src="item.icon || defaultAvatar" mode="aspectFill" />
          <view class="content">
            <view class="title">{{ item.name }}</view>
            <view class="desc">{{ item.description }}</view>
            <view class="chat-info">
              <view class="chat-count">{{ formatNumber(item.chatCount) }}万人聊过 · @{{ item.creatorName }}</view>
            </view>
          </view>
          <view class="add-btn" @tap.stop="handleAdd(item)">+</view>
        </view>
      </view>
    </scroll-view>

    <!-- 固定底部导航 -->
    <view class="fixed-footer">
      <view class="tab-bar">
        <view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
          @tap="switchTab(index)">
          <text class="iconfont" :class="tab.icon" />
          <text class="text">{{ tab.text }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
	import { ref,onMounted } from 'vue'
	import { useDeviceStore } from '@/stores'
	import { message } from '@/utils'
	import { system } from '@/utils/system'
	
	const deviceStore = useDeviceStore()
	const statusBarHeight = system.getStatusBarHeight()

	// 默认头像
	const defaultAvatar = '/static/images/default-avatar.png'

	// 搜索相关
	const searchKey = ref('')
	const originalList = ref([]) // 保存原始数据
	// 搜索处理
	const handleSearch = () => {
		const keyword = searchKey.value.trim().toLowerCase()
		if (!keyword) {
			deviceList.value = originalList.value // 搜索词为空时显示所有数据
			return
		}

		// 前端实现模糊搜索
		deviceList.value = originalList.value.filter(item =>
			item.name.toLowerCase().includes(keyword) ||
			item.description.toLowerCase().includes(keyword)
		)
	}

	// 标签配置 
	const tags = ['推荐']
	const currentTag = ref(0)


	// 底部导航配置
	const tabs = [{
			text: '对话',
			icon: 'icon-message'
		},
		{
			text: '发现',
			icon: 'icon-search'
		},
		{
			text: '创建',
			icon: 'icon-add'
		},
		{
			text: '通知',
			icon: 'icon-notification'
		},
		{
			text: '我的',
			icon: 'icon-user'
		}
	]
	const currentTab = ref(1) // 当前在发现页

	const switchTag = (index) => {
		currentTag.value = index
		currentPage.value = 1
		loadData()
	}
	// 列表数据
	const deviceList = ref([])
	const loading = ref(false)
	const refreshing = ref(false)
	const currentPage = ref(1)
	const pageSize = 10

	// 加载数据时保存原始列表
	// 修改 loadData 函数
	const loadData = async () => {
	  if (loading.value) return
	  loading.value = true
	
	  try {
	    const res = await deviceStore.loadPublicDevices({
	      current: currentPage.value,
	      size: pageSize,
	      category: currentTag.value === 0 ? '' : tags[currentTag.value]
	    })
	
	    if (res.code === 200) {
	      const records = res.data.records || []
	      // 修改这里的逻辑，避免重复添加
	      if (currentPage.value === 1) {
	        // 第一页直接替换
	        deviceList.value = records
	        originalList.value = records
	      } else {
	        // 后续页面，先检查是否有重复，只添加新的记录
	        const newRecords = records.filter(record => 
	          !deviceList.value.some(existingRecord => 
	            existingRecord.id === record.id
	          )
	        )
	        deviceList.value.push(...newRecords)
	        originalList.value.push(...newRecords)
	      }
	    } else {
	      throw new Error(res.message || '加载失败')
	    }
	  } catch (error) {
	    console.error('加载失败:', error)
	    uni.showToast({
	      title: error.message || '加载失败',
	      icon: 'none'
	    })
	  } finally {
	    loading.value = false
	    refreshing.value = false
	  }
	}

	// 其他方法保持不变...
	const loadMore = () => {
		currentPage.value++
		loadData()
	}

	// 修改刷新函数，2秒后重置
const refresh = async () => {
    if (refreshing.value) return
    refreshing.value = true
    await loadData()
    // 2秒后重置刷新状态
    setTimeout(() => {
        refreshing.value = false
        uni.stopPullDownRefresh()
    }, 800)
}
	

	const handleAdd = async (device) => {
	  try {
	    const res = await deviceStore.collectDevice(device.id)
	    if (res && res.code === 200) {
	      // 使用 uni.showToast 替代 message
	      uni.showToast({
	        title: '添加成功',
	        icon: 'success'
	      })
	      // 刷新列表
	      await loadData()
	    }
	  } catch (error) {
	    console.error('添加失败:', error)
	    uni.showToast({
	      title: error.message || '添加失败',
	      icon: 'none'
	    })
	  }
	}

	const formatNumber = (num) => {
		return ((num || 0) / 10000).toFixed(1)
	}

	// 切换标签页
	const switchTab = (index) => {
		const routes = [
			'/pages/index/index',
			'/pages/discover/discover',
			'/pages/create/create',
			'/pages/notification/notification',
			'/pages/my/my'
		]
		uni.switchTab({
			url: routes[index]
		})
	}

	onMounted(() => {
		loadData()
	})
</script>

<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f8f9fa;
  
  // 固定头部
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;

    // 导航栏
    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;
      background: #fff;
      border-bottom: 1px solid #f5f5f5;

      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }
    }

    // 搜索框
    .search-box {
      padding: 24rpx 30rpx;
      background: #fff;

      .search-input-box {
        display: flex;
        align-items: center;
        background: #f5f6f7;
        border-radius: 36rpx;
        padding: 16rpx 24rpx;

        .icon-search {
          margin-right: 12rpx;
          font-size: 28rpx;
          color: #999;
        }

        .search-input {
          flex: 1;
          height: 40rpx;
          min-height: 40rpx;
          font-size: 28rpx;
          color: #333;
        }

        .search-placeholder {
          color: #999;
        }
      }
    }

    // 标签栏
    .tag-scroll {
      padding: 0 30rpx;
      white-space: nowrap;
      background: #fff;
      height: 88rpx;
      border-bottom: 1px solid #f5f5f5;

      .tag-item {
        display: inline-block;
        padding: 24rpx 32rpx;
        margin-right: 24rpx;
        font-size: 28rpx;
        color: #666;
        position: relative;

        &.active {
          color: #007AFF;
          font-weight: 500;
        }

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  // 可滚动内容区域
  .scrollable-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(110rpx + env(safe-area-inset-bottom));
    background: #f8f9fa;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 20rpx;
	padding-top: 30rpx; // 添加顶部内边距
    
    // banner区域
    .banner-box {
      margin: 24rpx 30rpx;
      border-radius: 20rpx;
      overflow: hidden;
      position: relative;
      background: #fff;

      .banner-img {
        width: 100%;
        height: 200rpx;
      }

      .banner-text {
        position: absolute;
        left: 30rpx;
        top: 30rpx;
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }

      .banner-btn {
        position: absolute;
        left: 30rpx;
        bottom: 30rpx;
        background: rgba(255, 255, 255, 0.9);
        color: #007AFF;
        padding: 12rpx 32rpx;
        border-radius: 32rpx;
        font-size: 26rpx;
        font-weight: 500;
      }
    }

    // AI列表
    .device-list {
      padding: 0 30rpx;

      .device-item {
        display: flex;
        align-items: flex-start;
        padding: 24rpx;
        background: #fff;
        border-radius: 16rpx;
        margin-bottom: 20rpx;

        .avatar {
          width: 88rpx;
          height: 88rpx;
          border-radius: 44rpx;
          margin-right: 20rpx;
          background: #f5f6f7;
        }

        .content {
          flex: 1;
          min-width: 0;

          .title {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 8rpx;
            line-height: 1.4;
          }

          .desc {
            font-size: 26rpx;
            color: #666;
            line-height: 1.5;
            margin-bottom: 12rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }

          .chat-info {
            display: flex;
            align-items: center;

            .chat-count {
              font-size: 24rpx;
              color: #999;
            }
          }
        }

        .add-btn {
          width: 56rpx;
          height: 56rpx;
          flex-shrink: 0;
          border-radius: 28rpx;
          background: #007AFF;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 36rpx;
          margin-left: 20rpx;
          margin-top: 8rpx;
        }
      }
    }
  }

  // 固定底部导航
  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    
    .tab-bar {
      height: 110rpx;
      background: #fff;
      display: flex;
      align-items: center;
      border-top: 1rpx solid #eee;
      padding-bottom: env(safe-area-inset-bottom);

      .tab-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;

        .iconfont {
          font-size: 48rpx;
          margin-bottom: 6rpx;
        }

        .text {
          font-size: 24rpx;
        }

        &.active {
          color: #007AFF;
        }
      }
    }
  }
}

// 下拉刷新相关样式
:deep(.uni-scroll-view) {
  .uni-scroll-view-refresh {
    background: #f8f9fa;
  }
  
  .uni-scroll-view-refresh__spinner {
    color: #007AFF;
  }
}
</style>